//
//  MRMyCustomView.m
//  MoRan
//
//  Created by 黄轩 on 2024/1/28.
//  Copyright © 2024 MoRan. All rights reserved.
//

#import "MRMyCustomView.h"

@implementation MRMyCustomView

- (instancetype)initWithFrame:(CGRect)frame dataList:(NSArray *)dataList {
    if (self = [super initWithFrame:frame]) {
        _dataList = dataList;
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    NSInteger count = _dataList.count*2;
    NSLog(@"啊啊啊啊啊啊啊啊啊啊 %ld",count);
    CGPoint center = CGPointMake(rect.size.width / 2, rect.size.height / 2);
    CGFloat radius = MIN(rect.size.width, rect.size.height) / 2;
    CGFloat angle = 0;
    CGFloat angleIncrement = 2 * M_PI / count; // divide circle into 12 equal parts
    NSArray *colors = @[UIColorFromHex(0xB9E0FF), UIColorFromHex(0xDEF1FF)];
    
    for (int i = 0; i < count; i++) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:center];
        
        [path addArcWithCenter:center radius:radius startAngle:angle endAngle:angle + angleIncrement clockwise:YES];
        
        [[colors[i % 2] colorWithAlphaComponent:1.0] setFill];
        [path fill];
        
        [self drawTextAtAngle:angle withRadius:radius];
        
        angle += angleIncrement;
    }
}

- (void)drawTextAtAngle:(CGFloat)angle withRadius:(CGFloat)radius {
    //1. 计算圆的中心点和半径。
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);

    //在每个等分的弧形中间添加文字，文字朝向圆心。
    CGFloat textRadius = radius / 2;
    CGFloat textStartAngle = 0;
    CGFloat textEndAngle = M_PI / _dataList.count;
    for (int i = 0; i < _dataList.count*2; i++) {
        CGFloat textAngle = (textStartAngle + textEndAngle) / 2;
        CGFloat x = center.x + textRadius * cos(textAngle);
        CGFloat y = center.y + textRadius * sin(textAngle);
        
        // 创建文本图层
        CATextLayer *textLayer = [CATextLayer layer];
        NSString *str = _dataList[i%_dataList.count];
        textLayer.string = str;
        textLayer.fontSize = 16;
        textLayer.foregroundColor = UIColorFromHex(0x333333).CGColor;
        textLayer.alignmentMode = kCAAlignmentCenter;
        textLayer.bounds = CGRectMake(0, 0, 60, 30);
        textLayer.position = CGPointMake(x, y);
        textLayer.contentsScale = UIScreen.mainScreen.scale;
        
        // 计算文字方向
        CGPoint endPosition;
        endPosition.x = center.x + textRadius * cos(textAngle + M_PI);
        endPosition.y = center.y + textRadius * sin(textAngle + M_PI);
        CGFloat xDiff = endPosition.x - textLayer.position.x;
        CGFloat yDiff = endPosition.y - textLayer.position.y;
        CGFloat angleRadians = atan2(yDiff, xDiff);
        CATransform3D transform = CATransform3DMakeRotation(angleRadians, 0, 0, 1);
        textLayer.transform = transform;
        
        [self.layer addSublayer:textLayer];
        
        textStartAngle = textEndAngle;
        textEndAngle = (i + 2) * M_PI / _dataList.count;
    }
}

@end
